package com.starhub.application.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starhub.api.docwriting.dao.WritingRecordMapper;
import com.starhub.api.docwriting.entity.WritingRecord;
import com.starhub.application.agent.dao.ChatMessageMapper;
import com.starhub.application.agent.dao.ChatSessionMapper;
import com.starhub.application.message.dto.Message;
import com.starhub.application.message.result.AIChatMessageResult;
import com.starhub.application.message.result.AIChatSessionResult;
import com.starhub.application.message.result.ChatMessageVO;
import com.starhub.application.message.result.ChatSessionVO;
import com.starhub.application.message.service.IMessageStoreService;
import com.starhub.common.bean.agent.ChatMessage;
import com.starhub.common.bean.agent.ChatSession;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.utils.HubBeanUtils;
import com.starhub.utils.Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息存储服务实现类
 */
@Service
public class MessageStoreServiceImpl implements IMessageStoreService {
    
    // 临时使用内存存储消息，后续可以替换为数据库或ES
    private final Map<String, List<Message>> messageStore = new ConcurrentHashMap<>();
    
    @Autowired
    private ChatSessionMapper chatSessionMapper;
    
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private WritingRecordMapper writingRecordMapper;

    /**
     * 保存消息
     * @param message 消息对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveMessage(Message message) {
        // 检查session是否存在
        ChatSession chatSession = addChatMessageCount(message);
        
        // 创建消息记录
        ChatMessage chatMessage = ChatMessage.builder()
            .id(IdGenerator.generateId())
            .sessionId(message.getSessionId())
            .chatSessionId(chatSession.getId())
            .userId(Util.getLongValue(message.getUserId()))
            .role(message.getRole())
            .content(message.getContent())
            .callFuncName(message.getCallFuncName())
            .messageOrder(chatSession.getTotalMessages())
            .build();
        chatMessageMapper.insert(chatMessage);
        
        // 保存到内存
        messageStore.computeIfAbsent(message.getSessionId(), k -> new ArrayList<>())
                   .add(message);
        
        // 预留ES存储接口
        saveMessageToES(message);
        return chatSession.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveWriteRecord(Message message, Map<String, Object> additionalParams) {
        ChatSession chatSession = addChatMessageCount(message);
        WritingRecord record = WritingRecord.builder()
                .id(IdGenerator.generateId())
                .chatSessionId(chatSession.getId())
                .userId(Util.getLongValue(message.getUserId()))
                .sessionId(message.getSessionId())
                .content(message.getContent())
                .title(additionalParams.getOrDefault("topic_type", "").toString())
                .writingType(additionalParams.getOrDefault("odocTypeName", "").toString())
                .keywords(additionalParams.getOrDefault("keywords", "").toString())
                .remark(additionalParams.getOrDefault("supplement", "").toString())
                .build();
        writingRecordMapper.insert(record);

        // 保存到内存
        messageStore.computeIfAbsent(message.getSessionId(), k -> new ArrayList<>())
                   .add(message);

        // 预留ES存储接口
        saveMessageToES(message);
        return chatSession.getId();
    }

    private ChatSession addChatMessageCount(Message message) {
        // 检查session是否存在
        LambdaQueryWrapper<ChatSession> sessionWrapper = new LambdaQueryWrapper<>();
        sessionWrapper.eq(ChatSession::getSessionId, message.getSessionId());
        ChatSession existingSession = chatSessionMapper.selectOne(sessionWrapper);

        if (existingSession == null) {
            // 如果session不存在，创建新的session
            String title = message.getContent() != null ?
                    (message.getContent().length() > 25 ? message.getContent().substring(0, 25) : message.getContent())
                    : "";
            ChatSession newSession = ChatSession.builder()
                                                .id(IdGenerator.generateId())
                                                .sessionId(message.getSessionId())
                                                .userId(Util.getLongValue(message.getUserId()))
                                                .title(title)
                                                .totalMessages(1)
                                                .agentId(message.getAgentId())
                                                .build();
            chatSessionMapper.insert(newSession);
            return newSession;
        } else {
            // 如果session存在，更新消息总数
            existingSession.setTotalMessages(existingSession.getTotalMessages() + 1);
            chatSessionMapper.updateById(existingSession);
            return existingSession;
        }
    }

    /**
     * 获取会话的历史消息(对话过程中ai交互使用)
     * @param sessionId 会话ID
     * @param limit 获取的消息数量限制
     * @return 消息列表
     */
    @Override
    public List<Message> getHistoryMessages(String sessionId, int limit) {
        List<Message> messages = messageStore.get(sessionId);
        if (messages == null) {
            return new ArrayList<>();
        }
        
        // 获取最新的limit条消息
        int startIndex = Math.max(0, messages.size() - limit);
        return new ArrayList<>(messages.subList(startIndex, messages.size()));
    }
    
    /**
     * 获取用户的会话列表(分页)
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 会话列表
     */
    @Override
    public AIChatSessionResult getUserSessions(Long userId, Long agentId, int pageNum, int pageSize) {
        Page<ChatSession> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<ChatSession> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatSession::getUserId, userId)
               .eq(ChatSession::getAgentId, agentId)
               .orderByDesc(ChatSession::getCreateTime);
        IPage<ChatSession> sessions = chatSessionMapper.selectPage(page, wrapper);

        // 转换
        List<ChatSessionVO> result = sessions.getRecords().stream()
                .map(session -> HubBeanUtils.convert(session, ChatSessionVO.class))
                .toList();

        return AIChatSessionResult.success(result, sessions.getTotal(), sessions.getSize(), sessions.getCurrent());
    }
    
    /**
     * 获取指定会话的消息列表(分页)
     * @param userId 用户ID
     * @param chatId 会话ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 消息列表
     */
    @Override
    public AIChatMessageResult getSessionMessages(Long userId, Long chatId, int pageNum, int pageSize) {
        // 先查询会话是否存在且属于该用户
        LambdaQueryWrapper<ChatSession> sessionWrapper = new LambdaQueryWrapper<>();
        sessionWrapper.eq(ChatSession::getId, chatId)
                     .eq(ChatSession::getUserId, userId);
        ChatSession session = chatSessionMapper.selectOne(sessionWrapper);
        
        
        if (session == null) {
            return AIChatMessageResult.fail("会话不存在");
        }
        
        Page<ChatMessage> page = new Page<>(pageNum, pageSize);

        // 查询消息列表
        LambdaQueryWrapper<ChatMessage> messageWrapper = new LambdaQueryWrapper<>();
        messageWrapper.eq(ChatMessage::getChatSessionId, chatId)
                     .orderByAsc(ChatMessage::getMessageOrder);
        IPage<ChatMessage> messages = chatMessageMapper.selectPage(page, messageWrapper);

        List<ChatMessageVO> result = messages.getRecords().stream()
                .map(message -> HubBeanUtils.convert(message, ChatMessageVO.class))
                .toList();

        return AIChatMessageResult.success(
            result,
            messages.getTotal(),
            messages.getSize(),
            messages.getCurrent()
        );
    }
    
    @Override
    public void saveMessageToES(Message message) {
        // TODO: 实现ES存储逻辑
        // 1. 连接ES
        // 2. 构建索引
        // 3. 存储消息
    }
} 